package com.seari.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.security.Key;
import java.util.Map;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JwtTokenUtils {

	public static void main(String[] args) {
//        System.out.println(UUID.randomUUID().toString().replace("-",""));
		Claims claims = phaseToken("eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJhOGM3NDlhNmRiZGY0Yzg2YThiNTY5MTYyYzY0NWY4ZSIsInN1YiI6ImFkbWluIiwic3RhdGlvbk5hbWUiOiJvY2MiLCJpc3MiOiJzZWFyaU1ldHJvIiwiaWF0IjoxNTU4MzQzMTY3LCJleHAiOjE1NTg0Mjk1Njd9.PvrL_NYdhFMd6svTZ3aHSyYFQDFOq6b5z-yCNQ2l5k4");
		String uid = claims.get("uid").toString();
		System.out.println(uid);
    }
    private static Key generatorKey(){
        SignatureAlgorithm saa=SignatureAlgorithm.HS256;
        byte[] bin=DatatypeConverter.parseBase64Binary("598340c0e69d4a0ba662ad44aa0b082c");
        Key key=new SecretKeySpec(bin,saa.getJcaName());
        return key;
    }

    public static String generatorToken(Map<String,Object> payLoad){
        ObjectMapper objectMapper=new ObjectMapper();

        try {

            return Jwts.builder().setPayload(objectMapper.writeValueAsString(payLoad))
            .signWith(SignatureAlgorithm.HS256,generatorKey()).compact();

        } catch (JsonProcessingException e) {

            e.printStackTrace();
        }
        return null;
    }


    public static Claims phaseToken(String token){
        Jws<Claims> claimsJwt=Jwts.parser().setSigningKey(generatorKey()).parseClaimsJws(token);
      
        return claimsJwt.getBody();
    }
	
}
